<?php
/**
 * Created by PhpStorm.
 * User: LG
 * Date: 2018/7/2
 * Time: 17:39
 */

namespace app\admin\controller;


use app\common\model\Configuration;
use app\common\model\Contract;
use app\common\model\Customer;
use app\common\model\WorkOrder;
use app\common\model\Parts;
use app\common\model\Equipments;
use think\Db;
use think\Exception;

class Revieworder extends Base
{
    protected $Configuration;
    protected $workModel;
    protected $Contract;

    public function __construct()
    {
        parent::__construct();
        $this->Configuration = new Configuration();
        $this->workModel = new WorkOrder();
        $this->Contract = new Contract('administrative_user','administrative_log');
    }

    /**
     * 获取待审核的工单
     * 请求参数     请求类型      是否必须      说明
     * @author ligang
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @date time
     */
    public function index()
    {
        $whereArray = input('get.');

        $where = [];
        if (isset($whereArray['audit_status']) && !empty($whereArray['audit_status'])) {
            $where['audit_status'] = $whereArray['audit_status'];
        }
        if (isset($whereArray['username']) && !empty($whereArray['username'])) {
            $where['username'] = ['LIKE','%'.$whereArray['username'].'%'];
        }
        if (isset($whereArray['telphone']) && !empty($whereArray['telphone'])) {
            $where['telphone'] = $whereArray['telphone'];
        }

        if (isset($whereArray['contract_no']) && !empty($whereArray['contract_no'])) {
            $where['contract_no'] = $whereArray['contract_no'];
        }

        if (isset($whereArray['order_number']) && !empty($whereArray['order_number'])) {
            $where['order_number'] = $whereArray['order_number'];
        }

        if (isset($whereArray['datetimeStart']) && !empty($whereArray['datetimeStart'])) {
            if (isset($whereArray['datetimeEnd']) && !empty($whereArray['datetimeEnd'])) {
                $where['order_time'] = ['BETWEEN',[strtotime(date('Y-m-d 00:00:00',strtotime($whereArray['datetimeStart']))),strtotime(date('Y-m-d 23:59:59',strtotime($whereArray['datetimeEnd'])))]];
            }else{
                $where['order_time'] = ['BETWEEN',[strtotime(date('Y-m-d 00:00:00',strtotime($whereArray['datetimeStart']))),strtotime(date('Y-m-d 23:59:59',time()))]];
            }
        }else{
            if (isset($whereArray['datetimeEnd']) && !empty($whereArray['datetimeEnd'])) {
                $where['order_time'] = ['BETWEEN',[strtotime(date('Y-m-d 00:00:00',time())),strtotime(date('Y-m-d 23:59:59',strtotime($whereArray['datetimeEnd'])))]];
            }
        }

        $join = [
            ['rq_contract', 'rq_work_order.contract_id = rq_contract.contract_id'],
            ['rq_customer','rq_work_order.user_id = rq_customer.user_id','LEFT']
        ];

        $field = '
            rq_work_order.work_order_id,
            rq_work_order.order_number,
            rq_work_order.work_order_id,
            rq_work_order.combo_money,
            rq_work_order.order_time,
            rq_work_order.business_id,
            rq_contract.contract_no,
            rq_contract.eq_count,
            rq_contract.contract_id,
            rq_contract.nature,
            rq_contract.contract_money,
            rq_contract.for_core_cost,
            rq_customer.username
        ';
        $where['rq_contract.nature'] = 1; //只浏览商用客户
        $where['rq_work_order.is_delete'] = 0;
        $where['rq_work_order.work_order_status'] = 12;
        $where['rq_work_order.audit_status'] = 3;
        if (isset($whereArray['page']) && !empty($whereArray['page'])) {
            $page = $whereArray['page'];
        } else {
            $page = 1;
        }

        $listRows = intval($this->Configuration->getkey('pagesize'));
        $all_order = Db::name('work_order')->where($where)->join($join)->field($field)->page($page, $listRows)->select();

        $eq_join = [
            ['rq_equipments', 'rq_contract_equipment.equipments_id = rq_equipments.equipments_id']
        ];
        $eq_field = 'rq_equipments.equipments_name';

        $type = ['1' => '续费', '2' => '换芯', '3' => '新装', '4' => '拆机', '5' => '移机',
            '6' => '维修', '7' => '续费+维修', '8' => '换芯+维修', '9' => '移机(拆)', '10' => '移机(装)',
        ];

        $contract_equipment_where = [
            'rq_contract_equipment.is_delete'=>0,
            'rq_contract_equipment.state'=>1
        ];
        foreach ($all_order as $key => $value) {
            //如果是商用就获取折算台数，否则就去查询合同台数
            $contract_equipment_where['contract_id'] = $value['contract_id'];
            $eq_num = Db::name('contract_equipment')->where($contract_equipment_where)->join($eq_join)->field($eq_field)->select();
            if ($value['nature'] == 1) {
                $all_order[$key]['eq_num'] = $value['eq_count'];
            } else {
                $all_order[$key]['eq_num'] = count($eq_num);
            }
            $equipments_name = '';
            foreach ($eq_num as $k => $v) {
                $equipments_name .= ' ' . $v['equipments_name'];
            }
            $all_order[$key]['equipments_name'] = $equipments_name;

            switch ($value['nature']) {
                case 1:
                    $all_order[$key]['nature'] = '商用客户';
                    break;
                case 2:
                    $all_order[$key]['nature'] = '家用客户';
                    break;
                case 3:
                    $all_order[$key]['nature'] = '外接包年';
                    break;
                case 4:
                    $all_order[$key]['nature'] = '外接点餐';
                    break;
                case 5:
                    $all_order[$key]['nature'] = '购买客户';
                    break;
                default:
                    $all_order[$key]['nature'] = '未知客户';
            }

            $all_order[$key]['combo_money'] = number_format($value['combo_money'], 2);
            $all_order[$key]['for_core_cost'] = number_format($value['for_core_cost'], 2);
            $all_order[$key]['order_time'] = date('Y-m-d H:i:s', $value['order_time']);
            $all_order[$key]['business_id'] = $type[$value['business_id']];
        }
        $total = Db::name('work_order')->where($where)->join($join)->count('*');
        //获取当前页
        $data['page']['currentPage'] = $page;
        //计算共有多少页
        $data['page']['lastPage'] = intval(ceil($total / $listRows));;
        //每页显示数目
        $data['page']['listRows'] = $listRows;
        $data['page']['count'] = $total;
        $data['data'] = $all_order;

        $this->assign('Nowpage', $data['page']['currentPage']); //当前页
        $this->assign('allpage', $data['page']['lastPage']); //总页数
        $this->assign('count', $data['page']['count']);//总条数
        $this->assign('data', $data['data']);
        if (input('get.page')) {
            return json($data);
        }
        return $this->fetch('Revieworder/index');
    }

    /**
     * 审核通过
     * @author ligang
     * @return bool|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @date 2018/7/3 11:08
     */
    public function through()
    {
        $id = input('get.id');
        if (empty($id)) {
            $this->error('数据错误');
            return false;
        }
        $order_info = Db::table('rq_work_order')->where(['work_order_id' => $id])->find();
        if (empty($order_info)) {
            $this->error('数据异常');
            return false;
        }

        $contractModel = new Contract();
        $cttWhere['contract_id'] = $order_info['contract_id'];
        $cttData = $contractModel->selectOne($cttWhere);
        if (empty($cttData)) {
            $this->error('请联系行政核查工单数据',null,'',5);
            return false;
        }

        // 查询当前工单的工程人员
        $engineersWhere['engineers_id'] = $order_info['repair_id'];
        $engineersData = Db::name('engineers')->where($engineersWhere)->find();
        // 查询当前工单的合同信息
        $contractWhere['contract_id'] = $order_info['contract_id'];
        $contractData = Db::name('contract')->where($contractWhere)->find();

        if ($contractData['is_special'] == 1) {
            $this->error('特殊合同不能提交到业绩系统',null,'',5);
            return false;
        }

        // 查询当前工单的合同客户
        $customerWhere['user_id'] = $contractData['user_id'];
        $customerData = Db::name('customer')->where($customerWhere)->find();
        // 查询当前工单合同推荐人
        $userWhere['user_id'] = $contractData['introducer_id'];
        $userData = Db::name('customer')->where($userWhere)->find();
        //获取合同的申请人
        $applicant = Db::name('customer')->where(['user_id' => $contractData['applicant']])->find();

        if (true) {
            // 查询当前工单设备数量
            $contractEquipmentWhere['contract_id'] = $contractData['contract_id'];
            $contractEquipmentWhere['state'] = 1;
            $contractEquipmentWhere['is_delete'] = 0;
            $contractEquipmentData = Db::name('contract_equipment')->where($contractEquipmentWhere)->count();

            // post_data数据
            $post_data['is_explain'] = $contractData['is_explain'];
            $post_data['achievement_work_order_number'] = $order_info['order_number'];
            $post_data['achievement_work_order_type'] = $order_info['business_id'];
            $post_data['engineers_name'] = $engineersData['engineers_name'];
            $post_data['engineers_number'] = $engineersData['engineers_number'];//工程人员编号
            $post_data['contract_number'] = $contractData['contract_no'];
            $post_data['nature'] = $contractData['nature'];//客户类型
            $post_data['contract_customer'] = $customerData['username'];
            $post_data['contract_customer_id_card'] = $customerData['id_card'];

            $post_data['contract_introducer'] = (!empty($contractData['introducer_id'])) ? $userData['username'] : '';//转介绍人

            $post_data['applicant'] = $applicant['employee_id'];//申请人（员工编号）

            //如果转介绍入职了，转介绍就是申请人
            if ($userData['is_entry'] == 1) {
                $post_data['applicant'] = $userData['employee_id'];
            }

            $post_data['equipments_number'] = ($contractData['nature'] == 1) ? $contractData['eq_count'] : $contractEquipmentData;
            $post_data['request_time'] = time();

            //数据加密
            $key = date('Y') . "优" . date('m') . "合" . date("d") . "一" . date("H") . "众";
            $expiry = 10;
            $request_data['data'] = $this->dataEncode($post_data, $key, $expiry);
            // crm业绩系统接口地址
            $url = config('post_api');
            // 调用post_request发送请求
            $curResult = post_request($url, $request_data);
            $ApiResult = json_decode($curResult);
            $rank['contract_no'] = $contractData['contract_no'];
            if ($ApiResult->code == 1) {
                //组装合同等级关系数据
                $tmp = $ApiResult->data;
                foreach ($tmp as $k => $v) {
                    $rank[$k] = $v;
                }
                if (!isset($rank['apply_id']) && isset($rank['push_id'])) {
                    $rank['apply_id'] = $rank['push_id'];
                    unset($rank['push_id']);
                }
                if (!isset($rank['apply_name']) && isset($rank['push_name'])) {
                    $rank['apply_name'] = $rank['push_name'];
                    unset($rank['push_name']);
                }
                if ($userData) {
                    $rank['push_apply_id'] = $userData['employee_id'];
                    $rank['push_apply_name'] = $userData['username'];
                }
                Db::startTrans();
                try{
                    db('work_order')->where(['work_order_id'=>$id])->update(['audit_status'=>1]);
                    db('contract_rank')->insert($rank);
                    Db::commit();
                    $this->success('提交成功');
                    exit();
                }catch (\Exception $e){
//                    dump($e->getMessage());
                    Db::rollback();
                    $this->error('结算成功，工单更新或合同关系写入失败。');
                    exit();
                }
            } else {
                $this->error($ApiResult->msg,null,'',5);
                return false;
            }
        }

    }

    /**
     * 审核拒绝
     * @author ligang
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @date 2018/7/3 11:01
     */
    public function refused()
    {
        $id = input('get.id');
        if (empty($id)) {
            $this->error('数据错误');
            return false;
        }

        $order_info = Db::table('rq_work_order')->where(['work_order_id' => $id])->find();

        if (empty($order_info)) {
            $this->error('数据异常');
            return false;
        }

        $result = Db::table('rq_work_order')->where(['work_order_id' => $id])->setField('audit_status', 2);

        if ($result > 0) {
            $this->success('请联系行政说明拒绝原因',null,'',5);
            return false;
        }
        $this->error('操作失败');

    }

    /**
     * 合同详情
     * @author ligang
     * @Request contract_id             int    GET   合同ID
     * @return array
     */
    public function details()
    {
        //检验get参数
        if (input('?get.contract_id')){
            //获取参数并强制转换为int型
            $contract_id = input('get.contract_id');
        }else{
            return json(array('code'=>0,'msg'=>'缺少必要参数'));
        }
        $join = [
            ['rq_customer','rq_contract.user_id = rq_customer.user_id'],
            ['rq_contract_remark','rq_contract_remark.contract_no = rq_contract.contract_no','LEFT']
        ];
        $field = '
            rq_customer.employee_id,
            rq_customer.username,
            rq_customer.telphone,
            rq_customer.add_time,
            rq_customer.account_status,
            rq_customer.remark,
            rq_customer.user_address,
            rq_customer.user_type,
            rq_customer.province,
            rq_customer.city,
            rq_customer.area,
            rq_customer.birthday,
            rq_contract.contract_no,
            rq_contract.contract_id,
            rq_contract.introducer_id,
            rq_contract.applicant,
            rq_contract.receipt,
            rq_contract.water_pressure,
            rq_contract.contract_money,
            rq_contract.nature,
            rq_contract.contract_type,
            rq_contract.province as ht_province,
            rq_contract.city as ht_city,
            rq_contract.area as ht_area,
            rq_contract.address,
            rq_contract.original_parts,
            rq_contract.installed_time,
            rq_contract.recent_time,
            rq_contract.for_core_cost,
            rq_contract.for_core_cycle,
            rq_contract.for_core_time,
            rq_contract.moving_machine_number,
            rq_contract.renew_date,
            rq_contract.for_core_number,
            rq_contract.administrative_id,
            rq_contract.corporate_name,
            rq_contract.housing_property,
            rq_contract.exire_date,
            rq_contract_remark.remark as contract_remark,
            rq_customer.is_entry
            ';
        //获取数据
        $data = $this->Contract->details(['contract_id'=>$contract_id],$join,$field);

        //转换客户状态
        foreach ($data as $key => $value){
            if ($key == 'account_status'){
                if ($value == 1){
                    $data[$key] = "正常";
                }else{
                    $data[$key] = "冻结";
                }
                continue;
            }if ($key == 'contract_type'){
                if ($value == 0){
                    $data[$key] = "未升级VIP";
                }else{
                    $data[$key] = "已升级VIP";
                }
                continue;
            }if ($key == 'user_type'){
                if ($value == 1){
                    $data[$key] = "普通用户";
                }else{
                    $data[$key] = "VIP用户";
                }
                continue;
            }
            if ($key == 'exire_date'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'add_time'){
                $data[$key] = date('Y-m-d H:i:s',$value);
                continue;
            }
            if ($key == 'birthday'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'installed_time'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'recent_time'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'for_core_time'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'renew_date'){
                $data[$key] = date('Y-m-d',$value);
                continue;
            }
            if ($key == 'housing_property'){
                if ($value == 1){
                    $data[$key] = "公租房";
                }elseif ($value == 2){
                    $data[$key] = "廉租房";
                }elseif ($value == 3){
                    $data[$key] = "租赁";
                }else{
                    $data[$key] = "购买";
                }
                continue;
            }
            if ($key == 'nature'){
                //1.商用客户,2.家用客户,3外接包年,4.外接点餐,5.购买客户
                if ($value == 1){
                    $data[$key] = "商用客户";
                }elseif ($value == 2){
                    $data[$key] = "家用客户";
                }elseif ($value == 3){
                    $data[$key] = "外接包年";
                }elseif ($value == 4){
                    $data[$key] = "外接点餐";
                }else{
                    $data[$key] = "购买客户";
                }
                continue;
            }
        }
        //判断是否是员工
        if ($data['is_entry'] == 1){
            $data['is_entry'] = "是";
            $data['personnel_number'] = $data['employee_id'];
        }else{
            $data['is_entry'] = "否";
            $data['personnel_number'] = "";
        }

        //获取转介绍人
        $Customer = new Customer();
        $data['introducer_id'] = $Customer->selectOne(['user_id'=>$data['introducer_id']])[0]['username'];
        $data['applicant'] = $Customer->selectOne(['user_id'=>$data['applicant']])[0]['username'];

        //获取设备台数
        $data['EquipmentNumber'] = $this->Contract->getEquipmentNumber(['contract_id'=>$contract_id,'state'=>1,'rq_contract_equipment.is_delete'=>0]);
        //获取设备记录
        $Equipment_join = [
            ['rq_equipments','rq_contract_equipment.equipments_id = rq_equipments.equipments_id'],
        ];
        //查询设备字段
        $Equipment_field = 'rq_equipments.equipments_name,
                            rq_contract_equipment.id,
                            rq_contract_equipment.equipments_id,
                            rq_contract_equipment.equipments_number,
                            rq_contract_equipment.equipments_address,
                            rq_contract_equipment.moving_machine_number
                            ';
        $data['equipment'] = $this->Contract->contractEquipment(['contract_id'=>$contract_id,'state'=>1,'rq_contract_equipment.is_delete'=>0],$Equipment_join,$Equipment_field);
        $newArr = [];
        foreach ($data['equipment'] as $key => $value){
            $data['equipment'][$key]['Remark'] = $this->Contract->equipmentsRemark(['contract_equipment_id'=>$value['id']]);
            for($i=1;$i<=8;$i++){
                if ($i == 1 || $i == 6){
                    continue;
                }
                $record = $this->Contract->equipmentRecord($i,['equipment_id'=>$value['id']]);
                if ($record){
                    foreach ($record as $rk => $rv){
                        switch ($i){
                            case 1:
                                $type = "新装";
                                break;
                            case 2:
                                $type = "维修";
                                break;
                            case 3:
                                $type = "换芯";
                                break;
                            case 4:
                                $type = "拆机";
                                break;
                            case 5:
                                $type = "移机";
                                break;
                            case 6:
                                $type = "续费";
                                break;
                            case 7:
                                $type = "换芯+维修";
                                break;
                            case 8:
                                $type = "续费+维修";
                                break;
                            default:
                                $type = "未知类型";
                        }
                        $record[$rk]['type'] = $type;
                        $data['equipment'][$key]['record'][] = $record[$rk];
                    }
                }
            }
        }
//        dump($data);
        //合同操作记录
        $ContractLogWhere['contract_id'] = $contract_id;
        $ContractLog = $this->Contract->getContractLog($ContractLogWhere,[],'');
        foreach ($ContractLog as $clk=>$clv){
            $ContractLog[$clk]['do_time'] = date('Y-m-d H:i:s',$clv['do_time']);
            switch ($clv['do_type']){
                case 1:
                    $ContractLog[$clk]['do_type'] = "新增";
                    break;
                case 2:
                    $ContractLog[$clk]['do_type'] = "删除";
                    break;
                case 3:
                    $ContractLog[$clk]['do_type'] = "修改";
                    break;
                case 4:
                    $ContractLog[$clk]['do_type'] = "解绑";
                    break;
            }
        }
        //判断是哪个端的
        foreach ($ContractLog as $key => $value){
            switch ($value['terminal_type']){
                //总后台
                case 0:
                    if ($value['do_id'] == 0){
                        $ContractLog[$key]['name'] = '系统';
                        $ContractLog[$key]['title'] = '系统';
                        break;
                    }
                    $findUserJoin = [
                        ['rq_admin_auth_group','rq_admin_user.groupid = rq_admin_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_admin_user.id'=>$value['do_id']
                    ];
                    $findUserField = 'rq_admin_user.name,rq_admin_auth_group.title';
                    $admin_user = $this->Contract->findUser('admin_user',$findUserWhere,$findUserJoin,$findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
                //行政区域
                case 1:
                    $findUserJoin = [
                        ['rq_administrative_auth_group','rq_administrative_user.groupid = rq_administrative_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_administrative_user.id'=>$value['do_id']
                    ];
                    $findUserField = 'rq_administrative_user.name,rq_administrative_auth_group.title';
                    $admin_user = $this->Contract->findUser('administrative_user',$findUserWhere,$findUserJoin,$findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
                //运营中心
                case 2:
                    $findUserJoin = [
                        ['rq_operation_auth_group','rq_operation_user.groupid = rq_operation_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_operation_user.id'=>$value['do_id']
                    ];
                    $findUserField = 'rq_operation_user.name,rq_operation_auth_group.title';
                    $admin_user = $this->Contract->findUser('operation_user',$findUserWhere,$findUserJoin,$findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
            }
        }
        //获取合同原始配件
        $PartsObj = new Parts();
        $PartsWhere = [
            'contract_id'=>$contract_id,
            'is_original'=>1,
            'rq_equipments_parts.is_delete'=>0
        ];
        $PartsJoin = [
            ['rq_parts','rq_equipments_parts.parts_id = rq_parts.parts_id']
        ];
        $PartsField = 'parts_name,parts_number';
        $Parts = $PartsObj->getContractParts($PartsWhere,$PartsField,$PartsJoin);
        //追加原始配件
        $data['original_parts'] = $Parts;
        //获取设备名称（型号）
        $equipmentsObj = new Equipments();
        $Equipments_name = $equipmentsObj->getList();
        //追加合同操作记录
        $data['ContractLog'] = $ContractLog;
        //模板赋值
        $this->assign('data',$data);
        $this->assign('is_show',false);
        $this->assign('Equipments_name',$Equipments_name);
        //渲染模板
        return $this->fetch("administrative@contract/details");
    }

    /**
     * 补单列表
     * 请求参数     请求类型      是否必须      说明
     * @author ligang
     * @date 2018/10/25 15:44
     */
    public function replenishment()
    {
        $dir =  dirname(__FILE__);
        $path = substr($dir,0,stripos($dir,'runquan')).'rqjy/public/replenishment';
        $file = scandir($path);
        $file_data = [];
        foreach ($file as $key=>$value){
            if ($value == '.' || $value == '..'){
                continue;
            }
            //读取文件内容
            $data = require_once $path.'/'.$value;
            array_push($file_data,$data['param']);
        }
        foreach ($file_data as $k=>$v){
            $file_data[$k]['achievement_work_order_type'] = config('workorder_type')[$v['achievement_work_order_type']];
            $file_data[$k]['nature'] = config('nature')[$v['nature']];
            $file_data[$k]['is_explain'] = ($v['is_explain'] == 2) ? '无' : '有';
        }
        $this->assign('data',$file_data);
        return $this->fetch('Revieworder/replenishment');
    }

    /**
     * 补单操作
     * 请求参数     请求类型      是否必须      说明
     * @author ligang
     * @return bool
     * @throws Exception
     * @throws \ErrorException
     * @throws \think\exception\PDOException
     * @date 2018/10/26 9:24
     */
    public function perform()
    {
        $order_number = input('order_number');
        $dir =  dirname(__FILE__);
        $file_path = substr($dir,0,stripos($dir,'runquan')).'rqjy/public/replenishment/'.$order_number.'.php';
        if (!file_exists($file_path)){
            $this->error('补单信息不存在，请联系维护人员');
            return false;
        }
        //链接业绩mysql
        $db = Db::connect([
            // 数据库类型
            'type'        => 'mysql',
            // 数据库连接DSN配置
            'dsn'         => '',
            // 服务器地址
            'hostname'    => '127.0.0.1',
            // 数据库名
            'database'    => 'rq_achievement',
            // 数据库用户名
            'username'    => 'leuu_user',
            // 数据库密码
            'password'    => 'leuu_pass',
            // 数据库连接端口
            'hostport'    => '3306',
            // 数据库连接参数
            'params'      => [],
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
            // 数据库表前缀
            'prefix'      => 'rq_',
        ]);
        //读取文件内容
        $data = require_once $file_path;
        $db->startTrans();
        try{
            //更新考核业绩
            if (!empty($data['inspection_results'])){
                $db->table('rq_workers')->update($data['inspection_results']);
            }
            //更新业务员数据
            if (!empty($data['update_data'])){
                $db->table('rq_workers')->update($data['update_data']);
            }

            //更新直推人数据
            if (!empty($data['push_directly_update_data'])){
                $db->table('rq_workers')->update($data['push_directly_update_data']);
            }
            //更新经销商数据
            if (!empty($data['dealer_update_data'])){
                $db->table('rq_workers')->update($data['dealer_update_data']);
            }
            //更新星级经销商数据
            if (!empty($data['StarDealer_update_data'])){
                $db->table('rq_workers')->update($data['StarDealer_update_data']);
            }
            //更新2星级经销商数据
            if (!empty($data['TwoStarDealer_update_data'])){
                $db->table('rq_workers')->update($data['TwoStarDealer_update_data']);
            }
            //更新5星级经销商数据
            if (!empty($data['five_star_dealer_up_data'])){
                $db->table('rq_workers')->update($data['five_star_dealer_up_data']);
            }
            //更新10星级经销商数据
            if (!empty($data['ten_star_dealer_up_data'])){
                $db->table('rq_workers')->update($data['ten_star_dealer_up_data']);
            }
            //更新20星级经销商数据
            if (!empty($data['twenty_star_dealer_up_data'])){
                $db->table('rq_workers')->update($data['twenty_star_dealer_up_data']);
            }
            //2019年1月3日 新增
            if (isset($data['gma']) && !empty($data['gma'])){
                $db->table('rq_workers')->update($data['gma']);
            }
            if (isset($data['gm']) && !empty($data['gm'])){
                $db->table('rq_workers')->update($data['gm']);
            }
            $insert_data = [];
            //有无讲解
            if (!empty($data['is_explain'])) {
                $data['is_explain']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['is_explain']);
            }
            if (!empty($data['achievementWorkersData'])){
                $data['achievementWorkersData']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['achievementWorkersData']);
            }
            if (!empty($data['push_directly_data'])){
                $data['push_directly_data']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['push_directly_data']);
            }
            if (!empty($data['dealer'])){
                $data['dealer']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['dealer']);
            }
            if (!empty($data['StarDealer_data'])){
                $data['StarDealer_data']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['StarDealer_data']);
            }
            if (!empty($data['TwoStarDealer_data'])){
                $data['TwoStarDealer_data']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['TwoStarDealer_data']);
            }
            if (!empty($data['five_star_dealer_data'])){
                $data['five_star_dealer_data']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['five_star_dealer_data']);
            }
            if (!empty($data['ten_star_dealer_data'])){
                $data['ten_star_dealer_data']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['ten_star_dealer_data']);
            }
            if (!empty($data['twenty_star_dealer_data'])){
                $data['twenty_star_dealer_data']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['twenty_star_dealer_data']);
            }
            //2019年1月3日新增
            if (isset($data['engineers_dealer']) && !empty($data['engineers_dealer'])){
                $data['engineers_dealer']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['engineers_dealer']);
            }
            if (isset($data['gma_order_data']) && !empty($data['gma_order_data'])){
                $data['gma_order_data']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['gma_order_data']);
            }
            if (isset($data['gm_order_data']) && !empty($data['gm_order_data'])){
                $data['gm_order_data']['achievement_id'] = $data['achievement_id'];
                array_push($insert_data,$data['gm_order_data']);
            }
            if (isset($data['engineers']) && !empty($data['engineers'])){
                $db->table('rq_engineers')->update($data['engineers']);
            }
            if (isset($data['engineers_performance']) && !empty($data['engineers_performance'])){
                $data['engineers_performance']['achievement_id'] = $data['achievement_id'];
                $db->table('rq_engineers')->insert($data['engineers_performance']);
            }

            $db->table('rq_achievement_workers')->insertAll($insert_data);
            unlink($file_path);
            $db->commit();
            $this->success('补单成功',url('Revieworder/replenishment'));
//            $result = [
//                'code' => 1,
//                'msg'  => '补单成功',
//                'data' => '',
//                'url'  => url('Revieworder/replenishment'),
//                'wait' => 3,
//            ];
//            return json($result);
        }catch (\Exception $e){
            $db->rollback();
//            $result = [
//                'code' => 0,
//                'msg'  => '补单失败，失败原因：'.$e->getMessage(),
//                'data' => '',
//                'url'  => '',
//                'wait' => 5,
//            ];
            $this->error('补单失败，失败原因：'.$e->getMessage(),'','',5);
//            return json($result);
        }
    }

}